package com.me.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapUtil {

	
	public static Object mapToBean(Map map,Class type) throws IntrospectionException, InstantiationException, IllegalAccessException{
		BeanInfo beanInfo=Introspector.getBeanInfo(type);
		Object bean=type.newInstance();
		PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
		for(int i=0;i<propertyDescriptors.length;i++){
			PropertyDescriptor propertyDescriptor=propertyDescriptors[i];
			String propertyName=propertyDescriptor.getName();
			if(map.containsKey(propertyName)){
				Object value=map.get(propertyName);
				Object[] args=new Object[1];
				args[0]=value;
				try {
					propertyDescriptor.getWriteMethod().invoke(bean, args);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return bean;
	}
	
	
	/*
	 * 将2维数组转换为List
	 * param:一维长度，二维长度，待转换集合，列名
	 */
	public static List<Map<Object,Object>> arrayToList(int len1,int len2,List list,String[] colNames){
		Object[][] objarr=new Object[len1][len2];
		List<Map<Object,Object>> resultList=new ArrayList<>();
		list.toArray(objarr);
		
		for(int i=0;i<objarr.length;i++){
			Map<Object, Object> map=new HashMap();
			for(int j=0;j<objarr[i].length;j++){
				map.put(colNames[j], objarr[i][j]);
				System.out.println(colNames[j]+":"+objarr[i][j]);
			}
			resultList.add(map);
		}
		return resultList;
	
	}
}
